package com.cloudz.iptv.fragment.content.v1;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudz.iptv.R;
import com.cloudz.iptv.api.v1.AliTssServiceApi;
import com.cloudz.iptv.api.v1.HomePageServiceApi;
import com.cloudz.iptv.audio.AliTss;
import com.cloudz.iptv.fragment.BaseFragment;
import com.cloudz.iptv.player.base.DataInter;
import com.cloudz.iptv.player.base.ReceiverGroupManager;
import com.cloudz.iptv.utils.InPutJson;
import com.cloudz.iptv.utils.ResponseUtils;
import com.cloudz.iptv.utils.RetrofitUtils;
import com.cloudz.iptv.utils.SimplePreference;
import com.cloudz.iptv.utils.cache.ACache;
import com.cloudz.iptv.utils.cache.ACacheConstants;
import com.kk.taurus.playerbase.entity.DataSource;
import com.kk.taurus.playerbase.player.IPlayer;
import com.kk.taurus.playerbase.receiver.ReceiverGroup;
import com.kk.taurus.playerbase.widget.BaseVideoView;

import butterknife.BindView;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class Page1 extends BaseFragment
{
    private boolean isDestroyed = false;


    @BindView(R.id.videoView)
    BaseVideoView videoView;

    private ReceiverGroup mReceiverGroup;

    // 是否开始
    private boolean hasStart;

    private View view;


    @BindView(R.id.home_words)
    TextView words;

    @BindView(R.id.home_greetings)
    TextView greetings;

    private ACache aCache;


    private boolean flg = true;

    /**
     * 广告视频个数
     */
    private int adSize = 0;

    /**
     * 广告视频播放的索引
     */
    private int adIndex = 0;

    /**
     * 广告视频集合
     */
    private JSONArray adVideos;

    /**
     * 当前选中url
     */
    private String currentUrl;

    /**
     * 第一次进入
     */
    private boolean status = true;


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState)
    {
        super.onViewCreated(view, savedInstanceState);

        this.view = view;

        aCache = ACache.get(view.getContext());

        initPlayer();

        initData();
    }

    @Override
    public int getLayoutId()
    {
        return R.layout.activity_pager_1;
    }

    public void initPlayer()
    {

        if (!hasStart)
        {

            // 组装组件
            mReceiverGroup = ReceiverGroupManager.get().getReceiverGroup(this.getActivity());

            mReceiverGroup.getGroupValue().putBoolean(DataInter.Key.KEY_CONTROLLER_TOP_ENABLE, true);

            videoView.setReceiverGroup(mReceiverGroup);

            this.hasStart = true;
        }

    }


    public void initData()
    {

        HomePageServiceApi homePageServiceApi = RetrofitUtils.getInstance().createApi(SimplePreference.getServerUrl(this.getContext()), HomePageServiceApi.class);

        homePageServiceApi.getHomePage().enqueue(new Callback<ResponseBody>()
        {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response)
            {

                try
                {
                    InPutJson inOutJson = ResponseUtils.getInOutJson(response);

                    if (inOutJson.result)
                    {
                        JSONObject data = inOutJson.getJSONObject();
                        JSONObject welcome = data.getJSONObject("welcome");

                        if (!isDestroyed)
                        {
                            String o1 = welcome.getString("words");
                            words.setText(o1);

                            String o2 = welcome.getString("greetings");
                            greetings.setText("\t\t" + o2);

                            if (flg)
                            {
                                tss(o1 + o2);

                                flg = false;
                            }

                            // 广告
                            JSONObject ad = data.getJSONObject("ad");

                            // 视频
                            JSONArray videos = ad.getJSONArray("videos");

                            if (videos != null && !videos.isEmpty())
                            {
                                adVideos = videos;
                                adSize = videos.size();

                                if (status)
                                {
//                                    ijkVideoView.setUrl("http://221.174.127.122:20500/Live/CCTV1/shift.m3u8");

                                    currentUrl = "http://221.174.127.122:20500/Live/CCTV1/shift.m3u8"; //videos.getString(0);

                                    currentUrl = "http://httpdvb.slave.pygdzhcs.com:13164/playurl?playtype=live&protocol=hls&accesstoken=R5CC343B7U309FE166K775A33B0I6FD4AD75PBM306DC06V1020DZ225B8WE278B851C71&playtoken=31609SSUTVSTGQM1022234&auth=no&programid=4200000166";

                                    replay();
                                }

                            }

                            // 图片
                            JSONArray images = ad.getJSONArray("images");

                            if (images != null && !images.isEmpty())
                            {
                                aCache.put(ACacheConstants.AD_IMAGE_CACHE, images, ACacheConstants.CACHE_TIME * ACache.TIME_DAY);
                            }

                            status = false;


                        }
                    }
                } catch (Exception e)
                {
                    Log.d("homePage----->", "获取首页数据失败");

                    if (!isDestroyed)
                    {
                        String o1 = "尊敬的贵宾您好！";
                        words.setText(o1);


                        String o2 = "\t\t在您住店期间，我们将为您提供尽善尽美的服务，使您感受到温馨与真诚，愿我们的服务给您留下美好的印象。";
                        greetings.setText(o2);

                        tss(o1 + o2);
                    }

                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t)
            {

            }
        });
    }

    Handler handler = new Handler();

    /**
     * 语音播放
     *
     * @param msg
     */
    public void tss(String msg)
    {
        AliTssServiceApi aliTssServiceApi = RetrofitUtils.getInstance().createApi(SimplePreference.getServerUrl(this.getContext()), AliTssServiceApi.class);
        aliTssServiceApi.getAliYyToken().enqueue(new Callback<ResponseBody>()
        {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response)
            {

                try
                {
                    InPutJson inOutJson = ResponseUtils.getInOutJson(response);

                    if (inOutJson.result)
                    {
                        String data = inOutJson.data;

                        AliTss.getInstance().startSynthesizer(data, msg);

                        // 4 个字1s
                        int m = data.length() / 2;

                        handler.postDelayed(() ->
                        {
                        }, m * 1000);//x秒后执行Runnable中的run方法
                    }
                } catch (Exception e)
                {
                    Log.d("tts----->", "获取阿里语音token失败");
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t)
            {

            }
        });
    }


    /**
     * 重播
     */
    private void replay()
    {
        DataSource dataSource = new DataSource(currentUrl);

        videoView.setDataSource(dataSource);
        videoView.start();

    }
    @Override
    public void onPause()
    {
        super.onPause();

        int state = videoView.getState();
        if (state == IPlayer.STATE_PLAYBACK_COMPLETE)
            return;

        videoView.stop();
    }

    @Override
    public void onResume()
    {
        super.onResume();

        int state = videoView.getState();
        if (state == IPlayer.STATE_PLAYBACK_COMPLETE)
            return;

        replay();

    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        videoView.stopPlayback();
    }

    @Override
    public void onHiddenChanged(boolean hidden)
    {
        super.onHiddenChanged(hidden);

        if (hidden)
        {
            //Fragment隐藏时调用
            // 暂停
            videoView.stop();
        } else
        {
            //Fragment显示时调用
            replay();
        }
    }

    private void destroy()
    {
        if (isDestroyed)
        {
            return;
        }
        // 回收资源
        isDestroyed = true;
    }
}
